import redis

from app01.db import Dd

class RBAC:
    # 二进制授权
    def set_role(self,roleid,nobeid):
        # 查询角色有的id
        db=Dd()
        role=db.get_one("select * from novel_role where id=%s" % roleid)
        node=db.get_one("select * from novel_nobe where id=%s" % nobeid)
        bate=role['byte'] | node['byte']
        # 修改数据库
        db.update('update novel_role set byte=%s where id=%s' % (bate,roleid))

    # 查询用户的权限
    def get_role_node(self,userid):
        db = Dd()
        # 查询用户的角色id 权限
        res=db.get_all('select novel_role.name,novel_role.byte,novel_role.id from novel_user inner join novel_role on novel_user.roleid =novel_role.id where novel_user.id=%s' % userid)
        node=db.get_all("select * from novel_nobe")

        list=[]
        for i in node:
            for j in res:
                des=i['byte'] & j['byte']
                if des:
                    list.append(i)
        return list

# 队列
class Queue:
    def __init__(self):
        self.r = redis.Redis(host='127.0.0.1', port=6379, db=1, decode_responses=True)

    # 添加数据
    def set_insert(self, name, values):
        # 从尾部添加 列表
        return self.r.rpush(name, values)

    # 出队
    def del_queue(self, name):
        # 从头部删除户
        return self.r.lpop(name)

    # 获取数据长度
    def get_len_queue(self, name):
        return self.r.llen(name)

    # 获取所有数据
    def get_all_queue(self, name):
        return self.r.lrange(name, 0, -1)



import redis


class RedisCon():
    def __init__(self):
        self.conn = redis.Redis(host='127.0.0.1', port=6379, db=1, decode_responses=True)

    # 字符串存
    def str_set(self, key, value, time=0):
        if time == 0:
            return self.conn.set(key, value)
        else:
            # 设置过期时间，单位是秒
            return self.conn.setex(key, time, value)

    # 字符串读取
    def str_get(self, key):
        value = self.conn.get(key)
        if value:
            value = value
        return value

    # 删除
    def str_del(self, key):
        return self.conn.delete(key)

    def insert_zes(self, key,value):
        return self.conn.sadd(key,value)

    def get_all(self, key):
        val = self.conn.smembers(key)
        print(val)
        if  val:
            list = []
            for i in val:
                list.append(str(i))
            return list
        else:
            return None